<template>
  <div class="app-container">
    <div class="filter-container">
      <label style="font-size:20px ">评分项管理</label>
      <el-button class="filter-item" style="margin-left: 130px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增评分
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    ><el-table-column type="expand">
       <template>
         <el-form label-position="left" inline class="demo-table-expand">
           <el-row>
             <el-col :span="5">
               <el-form-item label="级别" style="display: block">
                 <span>{{ demp.rank1 }}-{{ demp.rank3 }}</span>
               </el-form-item></el-col>
             <el-col :span="19">
               <el-form-item label="描述" style="display: block">
                 <span>{{ demp.status }}</span>
               </el-form-item>
             </el-col></el-row>
           <el-row>
             <el-col :span="5">
               <el-form-item label="级别" style="display: block">
                 <span>{{ demp.rank2 }}-{{ demp.rank4 }}</span>
               </el-form-item></el-col>
             <el-col :span="19">
               <el-form-item label="描述" style="display: block">
                 <span>{{ demp.status2 }}</span>
               </el-form-item>
             </el-col></el-row>
         </el-form>
       </template>
     </el-table-column>
      <el-table-column label="编号" prop="name" width="110px" align="center" />
      <el-table-column label="名称" prop="phone" min-width="150px" />
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template>
          <el-button type="text" size="mini">
            修改
          </el-button>
          <el-button type="text" size="mini">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form ref="dynamicValidateForm" :model="dynamicValidateForm" label-width="100px" class="demo-dynamic">
          <el-form-item label="评分项名称" prop="title">
            <el-input v-model="temp.title" />
          </el-form-item>
          <el-form-item
            label="评分"
          >
            <el-select v-model="vu" style="width: 100px;margin-bottom: 10px;margin-right: 5px" placeholder="请选择">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>分<span style="margin-left: 10px;margin-right: 10px">-</span><el-select v-model="vu1" style="width: 100px;margin-bottom: 10px;margin-right: 5px" placeholder="请选择">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>分
            <el-input v-model="dynamicValidateForm.email" placeholder="请输入评分描述" />
          </el-form-item>
          <el-form-item
            v-for="(domain, index) in dynamicValidateForm.domains"
            :key="domain.key"
            :label="'评分' + index+2"
            :prop="'domains.' + index + '.value'"
            :rules="{
              required: true, message: '描述不能为空', trigger: 'blur'
            }"
          >
            <el-select v-model="vu3" style="width: 100px;margin-bottom: 10px;margin-right: 5px" placeholder="请选择">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>分<span style="margin-left: 10px;margin-right: 10px">-</span><el-select v-model="vu4" style="width: 100px;margin-bottom: 10px;margin-right: 5px" placeholder="请选择">
              <el-option
                v-for="item in cities"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>分
            <el-input v-model="domain.value" placeholder="请输入评分描述" /><el-button @click.prevent="removeDomain(domain)">删除</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="addDomain">新增评分</el-button>
            <el-button @click="resetForm('dynamicValidateForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm('dynamicValidateForm')">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogEditVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="教師" disabled>
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="用戶名" prop="title">
          <el-input v-model="temp.title" placeholder="William" disabled />
        </el-form-item>
        <el-form-item label="入职时间" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" disabled />
        </el-form-item>
        <el-form-item label="登录名" prop="title">
          <el-input v-model="temp.title" placeholder="William" disabled />
        </el-form-item>
        <el-form-item label="电话" prop="title">
          <el-input v-model="temp.title" disabled placeholder="12010001105" />
        </el-form-item>
        <el-form-item label="性別" prop="title">
          <el-input v-model="temp.title" disabled placeholder="男" />
        </el-form-item>
        <el-form-item label="状态" prop="title">
          <el-input v-model="temp.title" disabled placeholder="授課" />
        </el-form-item>
        <el-form-item label="总课时" prop="title">
          <el-input v-model="temp.title" disabled placeholder="200" />
        </el-form-item>
        <el-form-item label="微信号" prop="title">
          <el-input v-model="temp.title" disabled placeholder="12010001105" />
        </el-form-item>
        <el-form-item label="年齡" prop="title">
          <el-input v-model="temp.title" disabled placeholder="33" />
        </el-form-item>
        <el-form-item label="地址" prop="title">
          <el-input v-model="temp.title" disabled placeholder="三里屯" />
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: '教師' },
  { key: 'US', display_name: '学生' },
  { key: 'JP', display_name: '主任' },
  { key: 'EU', display_name: '校長' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter: function(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      cities: [{
        value: 'one',
        label: '一'
      }, {
        value: 'two',
        label: '二'
      }, {
        value: 'three',
        label: '三'
      }, {
        value: 'four',
        label: '四'
      }, {
        value: 'five',
        label: '五'
      }, {
        value: 'six',
        label: '六'
      }, {
        value: 'seven',
        label: '七'
      }, {
        value: 'eight',
        label: '八'
      }, {
        value: 'nine',
        label: '九'
      }, {
        value: 'ten',
        label: '十'
      }
      ],
      vu: '',
      vu1: '',
      vu3: '',
      vu4: '',
      value: '1',
      value2: ' ',
      tableKey: 0,
      list: null,
      dynamicValidateForm: {
        domains: [{
          value: ''
        }],
        email: ''
      },
      tableData: [{ name: '1', phone: '音准', role: '管理员', status: 1 },
        { name: '2', phone: '想象力', role: '教师', status: 0 },
        { name: '3', phone: '可塑性', role: '助教', status: 1 }],
      temp: {
        idcard: '120102199806022412', age: '22', sex: '男', address: '三里屯', phone: '15516217212', status: '平均水平', status2: '高于平均水平', rank1: '1 分', rank2: '4 分', rank3: '3 分', rank4: '6 分'
      },
      demp: {
        idcard: '120102199806022412', age: '22', sex: '男', address: '三里屯', phone: '15516217212', status: '平均水平', status2: '高于平均水平', rank1: '1 分', rank2: '4 分', rank3: '3 分', rank4: '6 分'
      },
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,
      dialogEditVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now()
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogEditVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
